package com.iking.toolkit.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.aspose.words.*;
import com.aspose.words.net.System.Data.DataRow;
import com.aspose.words.net.System.Data.DataTable;
import com.iking.toolkit.model.Msg;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.*;
import java.util.List;

import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.FontSettings;
import com.aspose.words.SaveFormat;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

/**
 * 功能描述：word，excel转换工具类
 *
 * @auther: xuesen
 * @date: 2022/9/21 9:16
 */
@Slf4j
public class AsposeUtil {
    /**
     * 将MultipartFile（Word/Excel）转换为PDF格式的MultipartFile
     * @param file 上传的Word（.doc/.docx）或Excel（.xls/.xlsx）文件
     * @return 转换后的PDF文件（MultipartFile）
     */
    public static Msg<MultipartFile> convertToPdf(MultipartFile file) {
        // 基础校验
        if (file.isEmpty()) {
            return Msg.fail("上传的文件为空，请重新上传");
        }

        // 获取文件名和后缀
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            return Msg.fail("文件名不存在");
        }
        String suffix = getFileSuffix(originalFilename);
        if (suffix == null) {
            return Msg.fail("文件后缀不存在，请检查文件格式");
        }
        // 关键：同步阶段读取文件内容到内存，脱离Tomcat临时文件依赖
        byte[] fileBytes;
        try {
            fileBytes = file.getBytes(); // 直接读取文件内容到字节数组
        } catch (IOException e) {
            log.error("读取文件内容失败，原文件名：{}", originalFilename, e);
            return Msg.fail("读取文件失败：" + e.getMessage());
        }
        // 临时文件处理
        File tempPdfFile = null;
        try {
            // 1. 创建临时PDF输出文件
            String tempPdfName = UUID.randomUUID() + ".pdf";
            tempPdfFile = File.createTempFile(tempPdfName, ".pdf");
            tempPdfFile.deleteOnExit();

            // 2. 从内存字节数组创建输入流，调用转换逻辑（不再依赖原MultipartFile的InputStream）
            try (InputStream inputStream = new ByteArrayInputStream(fileBytes)) {
                Msg<File> convertMsg = convert2Pdf(inputStream, tempPdfFile.getAbsolutePath(), suffix);
                if (!convertMsg.isSuccess()) {
                    return Msg.fail("转换失败：" + convertMsg.getMsg());
                }
            }

            // 3. 验证转换后的PDF文件
            if (tempPdfFile.length() == 0) {
                return Msg.fail("PDF文件生成失败，内容为空");
            }

            // 4. 将临时PDF文件转换为MultipartFile
            byte[] pdfBytes = Files.readAllBytes(tempPdfFile.toPath());
            String pdfFileName = originalFilename.replace("." + suffix, ".pdf"); // 替换后缀为.pdf

            MultipartFile resultFile = new MockMultipartFile(
                    "file",                // 表单字段名
                    pdfFileName,            // 转换后的文件名
                    "application/pdf",      // PDF的MIME类型
                    pdfBytes                // 文件字节流
            );

            log.info("文件转PDF成功，原文件名：{}，转换后大小：{} bytes",
                    originalFilename, resultFile.getSize());
            return Msg.sucess(resultFile);

        } catch (Exception e) {
            log.error("文件转PDF异常，原文件名：{}，后缀：{}", originalFilename, suffix, e);
            return Msg.fail("转换异常，原因：" + e.getMessage());
        } finally {
            // 清理临时文件
            if (tempPdfFile != null && tempPdfFile.exists() && !tempPdfFile.delete()) {
                log.warn("临时PDF文件清理失败：{}", tempPdfFile.getAbsolutePath());
            }
        }
    }

    /**
     * 提取文件后缀
     */
    private static String getFileSuffix(String filename) {
        if (filename.contains(".")) {
            return filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
        }
        return null;
    }
    /**
     * 转换附件为pdf
     *
     * @param sourcePath
     * @param targetPath
     * @return
     */
    public static Boolean convert2Pdf(String sourcePath, String targetPath) {
        boolean result = false;
        try (InputStream inputStream = Files.newInputStream(new File(sourcePath).toPath())) {
            String suffix = FileUtil.extName(sourcePath);
            if (ObjectUtil.equal("doc", suffix) || ObjectUtil.equal("docx", suffix)) {
                result = word2Pdf(inputStream, targetPath);
            } else if (ObjectUtil.equal("xls", suffix) || ObjectUtil.equal("xlsx", suffix)) {
                result = excel2Pdf(inputStream, targetPath);
            }
        } catch (Exception e) {
            log.error("aspose.words转pdf异常==>sourcePath={}, targetPath={}", sourcePath, targetPath, e);
        }
        return result;
    }

    /**
     * 转换附件为pdf
     *
     * @return
     */
    public static Msg<File> convert2Pdf(InputStream inputStream, String targetPath, String suffix) {
        try {
            if (ObjectUtil.equal("doc", suffix) || ObjectUtil.equal("docx", suffix)) {
                return word2PdfMsg(inputStream, targetPath);
            } else if (ObjectUtil.equal("xls", suffix) || ObjectUtil.equal("xlsx", suffix)) {
                return excel2PdfMsg(inputStream, targetPath);
            } else {
                return Msg.fail("无法转换");
            }
        } catch (Exception e) {
            log.error("aspose.words转pdf异常==>suffix={}, targetPath={}", suffix, targetPath, e);
            return Msg.fail("aspose.words转pdf异常,异常原因：" + e);
        }
    }


    /**
     * 将word转pdf
     *
     * @param sourcePath
     * @param targetPath
     * @return
     */
    public static Boolean word2Pdf(String sourcePath, String targetPath) {
        boolean result = false;
        try (InputStream inputStream = Files.newInputStream(new File(sourcePath).toPath())) {
            result = word2Pdf(inputStream, targetPath);
        } catch (Exception e) {
            log.error("aspose.words转pdf异常==>sourcePath={}, targetPath={}", sourcePath, targetPath, e);
        }
        return result;
    }

    /**
     * 将word转pdf
     *
     * @param sourceFile
     * @param targetPath
     * @return
     */
    public static Boolean word2Pdf(File sourceFile, String targetPath) {
        boolean result = false;
        try (InputStream inputStream = Files.newInputStream(sourceFile.toPath())) {
            result = word2Pdf(inputStream, targetPath);
        } catch (Exception e) {
            log.error("aspose.words转pdf异常==>sourceFile={}, targetPath={}", sourceFile.getAbsolutePath(), targetPath, e);
        }
        return result;
    }


    /**
     * 将excel转pdf
     *
     * @param inputStream
     * @param targetPath
     * @return
     */
    public static Msg<File> excel2PdfMsg(InputStream inputStream, String targetPath) {
        long startTime = System.currentTimeMillis();
        int sourFileSize = 0;
        try {
            sourFileSize = inputStream.available();
            // 1.校验license
            if (!getCellsLicense()) {
                return Msg.fail("校验license失败");
            }
            // 2.转换
            Workbook workbook = new Workbook(inputStream);
            // 2.1.设置转换属性
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            // true：将一页sheet打印到一页pdf；false：sheet会被分页
            pdfSaveOptions.setOnePagePerSheet(true);
            workbook.save(targetPath, pdfSaveOptions);
            log.info("aspose.cells转pdf耗时：{}，sourFileSize={}，targetFile={}", (System.currentTimeMillis() - startTime),
                    sourFileSize, targetPath);
            File file = new File(targetPath);
            return Msg.sucess(file);
        } catch (Exception e) {
            log.error("aspose.cells转pdf异常==>targetPath={}", targetPath, e);
            return Msg.fail("aspose.cells转pdf异常==>targetPath=" + targetPath + " ; e=" + e);
        }
    }

    /**
     * 将word转pdf
     *
     * @param inputStream
     * @param targetPath
     * @return
     */
    public static Boolean word2Pdf(InputStream inputStream, String targetPath) {
        long startTime = System.currentTimeMillis();
        boolean result = false;
        int sourFileSize = 0;
        try {
            sourFileSize = inputStream.available();
            // 1.校验license
            if (!getWordsLicense()) {
                return result;
            }
            // 2.转换
            LoadOptions options = new LoadOptions();
            options.setEncoding(StandardCharsets.UTF_8);
            Document doc = new Document(inputStream, options);
            doc.save(targetPath, SaveFormat.PDF);
            result = true;
        } catch (Exception e) {
            log.error("aspose.words转pdf异常==>targetPath={}", targetPath, e);
        }
        log.info("aspose.words转pdf耗时：{}，sourFileSize={}，targetFile={}", (System.currentTimeMillis() - startTime),
                sourFileSize, targetPath);
        return result;
    }

    /**
     * 将word转pdf
     *
     * @param inputStream
     * @param targetPath
     * @return
     */
    public static Msg<File> word2PdfMsg(InputStream inputStream, String targetPath) {
        long startTime = System.currentTimeMillis();
        int sourFileSize = 0;
        try {
            sourFileSize = inputStream.available();
            // 1.校验license
            if (!getWordsLicense()) {
                return Msg.fail("校验license失败");
            }
            // 2.转换
            LoadOptions options = new LoadOptions();
            options.setEncoding(StandardCharsets.UTF_8);
            Document doc = new Document(inputStream, options);
            doc.save(targetPath, SaveFormat.PDF);
            log.info("aspose.words转pdf耗时：{}，sourFileSize={}，targetFile={}", (System.currentTimeMillis() - startTime),
                    sourFileSize, targetPath);
            File file = new File(targetPath);
            return Msg.sucess(file);
        } catch (Exception e) {
            log.error("aspose.words转pdf异常==>targetPath={}", targetPath, e);
            return Msg.fail("aspose.words转pdf异常==>targetPath=" + targetPath + " ; e=" + e);
        }

    }

    /**
     * 将word转pdf
     *
     * @param sourcePath
     * @param targetPath
     * @return
     */
    public static Boolean excel2Pdf(String sourcePath, String targetPath) {
        boolean result = false;
        try (InputStream inputStream = Files.newInputStream(new File(sourcePath).toPath())) {
            result = excel2Pdf(inputStream, targetPath);
        } catch (Exception e) {
            log.error("aspose.cells转pdf异常==>sourcePath={}, targetPath={}", sourcePath, targetPath, e);
        }
        return result;
    }

    /**
     * 将word转pdf
     *
     * @param sourceFile
     * @param targetPath
     * @return
     */
    public static Boolean excel2Pdf(File sourceFile, String targetPath) {
        boolean result = false;
        try (InputStream inputStream = Files.newInputStream(sourceFile.toPath())) {
            result = excel2Pdf(inputStream, targetPath);
        } catch (Exception e) {
            log.error("aspose.cells转pdf异常==>sourceFile={}, targetPath={}", sourceFile.getAbsolutePath(), targetPath, e);
        }
        return result;
    }

    /**
     * 将excel转pdf
     *
     * @param inputStream
     * @param targetPath
     * @return
     */
    public static Boolean excel2Pdf(InputStream inputStream, String targetPath) {
        long startTime = System.currentTimeMillis();
        boolean result = false;
        int sourFileSize = 0;
        try {
            sourFileSize = inputStream.available();
            // 1.校验license
            if (!getCellsLicense()) {
                return Boolean.FALSE;
            }
            // 2.转换
            Workbook workbook = new Workbook(inputStream);
            // 2.1.设置转换属性
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            // true：将一页sheet打印到一页pdf；false：sheet会被分页
            pdfSaveOptions.setOnePagePerSheet(true);
            workbook.save(targetPath, pdfSaveOptions);
            result = true;
        } catch (Exception e) {
            log.error("aspose.cells转pdf异常==>targetPath={}", targetPath, e);
        }
        log.info("aspose.cells转pdf耗时：{}，sourFileSize={}，targetFile={}", (System.currentTimeMillis() - startTime),
                sourFileSize, targetPath);
        return result;
    }

    /**
     * 设置aspose.words的license
     *
     * @return
     */
    private static Boolean getWordsLicense() {
        try {
            ClassPathResource resource = new ClassPathResource("aspose/license.xml");
            License license = new License();
            license.setLicense(resource.getInputStream());
            return Boolean.TRUE;
        } catch (Exception e) {
            log.error("校验aspose.words中license异常==>", e);
        }
        return Boolean.FALSE;
    }

    /**
     * 设置aspose.cells的license
     *
     * @return
     */
    private static Boolean getCellsLicense() {
        try {
            ClassPathResource resource = new ClassPathResource("aspose/license.xml");
            com.aspose.cells.License license = new com.aspose.cells.License();
            license.setLicense(resource.getInputStream());
            return Boolean.TRUE;
        } catch (Exception e) {
            log.error("校验aspose.cells中license异常==>", e);
        }
        return Boolean.FALSE;
    }

    /**
     * 填充word模板
     *
     * @param inputStream
     * @param outputStream
     * @param dataMap
     * @throws Exception
     */
    public static void fillData4WordTemplate(InputStream inputStream,
                                             OutputStream outputStream,
                                             Map<String, Object> dataMap) throws Exception {
        // 1.校验license
        if (!getWordsLicense()) {
            return;
        }
        // 1.2.属性
        if (ObjectUtil.isNull(inputStream) || ObjectUtil.isNull(outputStream)) {
            log.info("填充word模板失败==>必填参数为空");
            return;
        }
        dataMap = ObjectUtil.defaultIfNull(dataMap, new HashMap<>(0));
        // 2.读取模板
        Document document = new Document(inputStream);
        // 3.填充
        List<String> keyList = new ArrayList<>();
        List<Object> valueList = new ArrayList<>();
        for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
            if (entry.getValue() instanceof Collection) {
                // 3.1.填充list
                JSONArray rowList = JSONUtil.parseArray(entry.getValue(), Boolean.FALSE);
                DataTable dataTable = getFillDataTable4WordTemplate(entry.getKey(), rowList);
                if (ObjectUtil.isNotNull(dataTable)) {
                    document.getMailMerge().executeWithRegions(dataTable);
                }
            } else {
                // 3.2.填充data
                keyList.add(entry.getKey());
                valueList.add(StrUtil.isNullOrUndefined(Convert.toStr(entry.getValue()))
                        ? StrUtil.EMPTY : entry.getValue());
            }
        }
        if (CollUtil.isNotEmpty(keyList)) {
            String[] keysArr = keyList.toArray(new String[keyList.size()]);
            Object[] valuesArr = valueList.toArray(new Object[valueList.size()]);
            document.getMailMerge().execute(keysArr, valuesArr);
        }
        // 4.写出
        document.save(outputStream, SaveOptions.createSaveOptions(SaveFormat.DOCX));
    }

    public static void fillData4WordTemplateByPlaceholder(InputStream inputStream,
                                                          OutputStream outputStream,
                                                          Map<String, Object> dataMap) throws Exception {
        // 1.校验license
        if (!getWordsLicense()) {
            return;
        }
        // 1.2.属性
        if (ObjectUtil.isNull(inputStream) || ObjectUtil.isNull(outputStream)) {
            log.info("填充word模板失败==>必填参数为空");
            return;
        }
        dataMap = ObjectUtil.defaultIfNull(dataMap, new HashMap<>(0));
        // 2.读取模板
        Document document = new Document(inputStream);
        for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
            // 3.填充data
            document.getRange().replace(entry.getKey(), StrUtil.isNullOrUndefined(Convert.toStr(entry.getValue()))
                    ? StrUtil.EMPTY : String.valueOf(entry.getValue()), Boolean.TRUE, Boolean.FALSE);
        }
        // 4.写出
        document.save(outputStream, SaveOptions.createSaveOptions(SaveFormat.DOCX));
    }

    /**
     * 获取填充word模板的数据列表
     *
     * @param tableName
     * @param rowList
     * @return
     * @throws Exception
     */
    private static DataTable getFillDataTable4WordTemplate(String tableName, JSONArray rowList) throws Exception {
        if (StringUtils.isEmpty(tableName) || CollUtil.isEmpty(rowList)) {
            return null;
        }
        // 1.创建表格
        DataTable dataTable = new DataTable(tableName);
        // 2.创建列
        rowList.getJSONObject(0).keySet().forEach(e -> dataTable.getColumns().add(e));
        // 3.创建行
        for (int i = 0; i < rowList.size(); i++) {
            DataRow dataRow = dataTable.newRow();
            // 3.1.填充行属性
            rowList.getJSONObject(i).forEach((k, v) ->
                    dataRow.set(k, StrUtil.isNullOrUndefined(Convert.toStr(v)) ? StrUtil.EMPTY : v));
            dataTable.getRows().add(dataRow);
        }
        return dataTable;
    }

    /**
     * 合并word
     *
     * @param sourcePathList
     * @param targetPath
     * @throws Exception
     */
    public static void mergeWord(List<String> sourcePathList, String targetPath) throws Exception {
        // 1.校验license
        if (!getWordsLicense()) {
            return;
        }
        if (StringUtils.isEmpty(targetPath)) {
            return;
        }
        if (CollUtil.isEmpty(sourcePathList)) {
            File targetFile = new File(targetPath);
            targetFile.createNewFile();
            return;
        }
        // 2.合并
        Document targetDocument = null;
        for (String sourcePath : sourcePathList) {
            if (ObjectUtil.isNull(targetDocument)) {
                targetDocument = new Document(sourcePath);
                continue;
            }
            Document sourceDocument = new Document(sourcePath);
            targetDocument.appendDocument(sourceDocument, ImportFormatMode.KEEP_SOURCE_FORMATTING);
        }
        // 3.写出
        if (ObjectUtil.isNotNull(targetDocument)) {
            targetDocument.save(targetPath, SaveFormat.DOCX);
        }
    }

}
